<template>
  <view class="sun-index">
    <view class="sun-logo-box">
      <view class="sun-logo">
<!--        <up-image-->
<!--            src="../../static/shalu_logo.png"-->
<!--            width="200rpx"-->
<!--            height="220rpx"-->
<!--            class="asset-img"-->
<!--        />-->
        <image src="../../static/shalu_logo.png" class="asset-img"/>
      </view>
      <!-- <text class="logo-text">正在保护你的资产</text> -->
    </view>
    <up-form class="login-form" :model="state" ref="login">
      <view class="input-label">账号：</view>
      <up-input
          v-model="state.mobile"
          :placeholder="$t('login.enterMobile')"
          :customStyle="{
          margin: '40rpx 60rpx', 
          fontSize: '36rpx',
          height: '100rpx',
          padding: '20rpx'
        }"
      >
        <template #suffix>
          <up-icon
              name="close"
              size="40"
              @click="state.mobile = ''"
              class="login-icon"
          ></up-icon>
        </template>
      </up-input>

      <view class="input-label">密码:</view>
      <up-input
          v-model="state.password"
          :password="!showPassword"
          :placeholder="$t('login.enterPassword')"
          :customStyle="{
          margin: '40rpx 60rpx', 
          fontSize: '36rpx',
          height: '100rpx',
          padding: '20rpx'
        }"
      >
        <template #suffix>
          <up-icon
              name="eye-off"
              class="login-icon"
              size="40"
              v-if="showPassword"
              @click="showPassword = false"
          ></up-icon>
          <up-icon
              name="eye-fill"
              class="login-icon"
              size="40"
              v-if="!showPassword"
              @click="showPassword = true"
          ></up-icon>
        </template>
      </up-input>

      <view class="login-config">
        <up-checkbox
            :label="$t('login.rememberPassword')"
            class="login-check"
            usedAlone
            v-model:checked="state.rememberPassword"
            iconSize="20"
            labelSize="20"
        >
        </up-checkbox>
        <view>
          <a style="font-size: 36rpx; color: #4792fd;" @click="languageShow = true">
            {{ $t("language") }}
          </a>
          <up-action-sheet
              :show="languageShow"
              :actions="actions"
              title="请选择语言"
              @select="onSelect"
              @close="languageShow = false"
          />
        </view>
      </view>
    </up-form>
    <view class="login-btn-box">
      <up-button
          v-show="showActivate"
          class="login-btn"
          text="激活"
          size="large"
          color="#F36A5A"
          @click="handleActivate"
          :customStyle="{
          height: '80rpx',
          fontSize: '40rpx',
          marginBottom: '20rpx'
        }"
      />
      <up-button
          class="login-btn"
          @click="handleSubmit"
          :text="$t('login.name')"
          size="large"
          color="rgb(71, 146, 253)"
          :customStyle="{
          height: '120rpx',
          fontSize: '40rpx'
        }"
      />
<!--      <up-button-->
<!--          class="login-btn"-->
<!--          @click="handleIMEI"-->
<!--          text="IMEI"-->
<!--          size="large"-->
<!--          color="rgb(71, 146, 253)"-->
<!--          :customStyle="{-->
<!--          height: '120rpx',-->
<!--          fontSize: '40rpx',-->
<!--		      marginTop: '10rpx'-->
<!--        }"-->
<!--      />-->
      <view style="padding: 20rpx 10rpx;display: flex;flex-direction: row;">
        <span style="margin-left: auto;color: #4792FD;cursor: pointer" @click="handleIMEI">获取本机授权码</span>
      </view>
    </view>
    <view class="version-container">
      <span>{{APP_VERSION}}</span>
    </view>
    <up-modal
        :show="showIMEI"
        title="IMEI信息"
        :closeOnClickOverlay="true"
        @close="showIMEI = false"
        :showCancelButton="false"
        confirmText="确定"
        @confirm="showIMEI = false">
      <view>{{imei}}</view>
    </up-modal>
  </view>
</template>
<script setup>
import {reactive, ref, defineOptions, onMounted} from "vue";
import {t, changeLocale} from "@/locale/index.js";
import {onLoad} from "@dcloudio/uni-app";
import http from "@/api/request";
import md5 from "js-md5";
import {APP_VERSION} from "@/utils/version";

defineOptions({
  options: {styleIsolation: "shared"},
});
const state = reactive({
  mobile: "",
  password: "",
  code: "",
  rememberPassword: false,
  language: "zh",
});

const showPassword = ref(false);
const codeSrc = ref("");
const showActivate = ref(false)
const userId = ref('')
const sessionId = ref('')
const showIMEI = ref(false)
const imei = ref('')

const languageShow = ref(false);

const actions = [
  {name: "中文", value: "zh"},
  {name: "English", value: "en"},
];

onLoad(() => {
  const token = uni.getStorageSync("token");
  if (token) {
    // 已登录，直接跳首页
    uni.switchTab({
      url: "/pages/home/home",
    });
  }
});

onMounted(() => {
  const saved = uni.getStorageSync("loginInfo");
  if (saved && saved.remember) {
    state.mobile = saved.mobile;
    state.password = saved.password;
    state.rememberPassword = true;
  }
});

const onSelect = (item) => {
  state.language = item.value;
  uni.setStorageSync("locale", item.value);
  changeLocale(item.value);
  uni.setLocale(item.value);
  languageShow.value = false;
};

const handleActivate = () => {
  http.post('/api/module/GetViewTable', {
    code: "getUserActivatePage",
    allColumnFilter: true,
    filters: [
      {
        name: 'user_id',
        value: userId.value
      },
      {
        name: 'audit_status',
        value: 0
      }
    ],
    pageInput: {currentPage: 1, pageSize: 999},
    permissionKey: "",
  }, {
    'Authorization': sessionId.value
  }).then(res => {
    if (res.result.viewTable && res.result.viewTable.length > 0) {
      uni.showToast({title: '数据已提交，请等待审核', duration: 1500, icon: "error"});
    } else {
      const params = {
        pageId: 'a0835913-d793-4cc1-a47b-fa08116cb98f',
        methodName: "doSaveTableData",
        saveTableDataRequest: {
          data: {
            insert: {
              useractivatemstr: {
                user_id: userId.value
              }
            },
            update: {},
            remove: {},
            updateWhere: {},
            removeWhere: {},
            otherData: {
              fileAttachments: [],
            },
            savedInvoke: {},
            pageAuths: [],
          },
        }
      }
      http.post('/api/module/Invoke', params, {
        'Authorization': sessionId.value
      }).then(resp => {
        if (resp.code === 1) {
          uni.showToast({title: '提交数据成功', duration: 1500, icon: "success"});
        } else {
          uni.showToast({title: '提交数据失败', duration: 1500, icon: "error"});
        }
      }).catch(err => {
        console.error(err)
        uni.showToast({title: '提交数据失败', duration: 1500, icon: "error"});
      })
    }
  }).catch(err => {
    console.error(err)
    uni.showToast({title: '获取数据失败', duration: 1500, icon: "error"});
  })
}


const handleIMEI = () => {
	let uuid = uni.getStorageSync('uuid')
  // imei.value = uuid.substring(0,7) + uuid.substring(7, uuid.length)
  imei.value = uuid
  showIMEI.value = true
}

function handleSubmit() {
  uni.showLoading({
    title: "登录中...",
    mask: true,
  });
  if (!state.mobile)
    return uni.showToast({
      title: t("login.enterMobile"),
      icon: "none",
      duration: 1500,
    });
  if (!state.password)
    return uni.showToast({
      title: t("login.enterPassword"),
      icon: "none",
      duration: 1500,
    });
  // if (!state.code) {
  //   return uni.showToast({
  //     title: t("login.enterCode"),
  //     icon: "none",
  //     duration: 1500,
  //   });
  // }
  let encryptedPassword = "";
  const isMD5 = (str) => /^[a-f0-9]{32}$/.test(str);

  if (state.rememberPassword && isMD5(state.password)) {
    encryptedPassword = state.password;
  } else {
    encryptedPassword = md5(state.password);
  }

  const data = {
    Password: encryptedPassword,
    UsernameOrEmailAddress: state.mobile,
    clientId: "",
    loginType: 2,
    loginWay: "All",
  };

  http.post("/api/account/doLogin", data).then((res) => {
    if (res.success && res.code) {
      sessionId.value = res["x-sessionId"]
      http.post('/api/module/Invoke', {
        "pageCode": "useractivate",
        "params": {
          "args": [{
            "name": "interfaceCode",
            "value": "Useractivate.checkActivate"
          },
            {
              "name": "uuid",
              "value": uni.getStorageSync('uuid')
            }]
        },
        "methodName": "checkActivate"
      }, {
        'Authorization': sessionId.value
      }).then(resp => {
        if (resp.code === -1) {
            showActivate.value = true
            userId.value = resp.error
            uni.hideLoading()
            uni.showToast({ title: '您的试用已结束', duration: 1500, icon: "error" });
        } else if (resp.code === -2) {
          userId.value = resp.error
          uni.hideLoading()
          uni.showToast({ title: '请先绑定设备', duration: 1500, icon: "error" });
        } else {
          uni.setStorageSync("token", res["x-sessionId"]);
          uni.setStorageSync("loginInfo", {
            mobile: state.mobile,
            password: encryptedPassword,
            remember: true,
          });
          uni.showToast({
            title: t("common.success"),
            duration: 1500,
            icon: "success",
          });
          setTimeout(() => {
            uni.switchTab({
              url: "/pages/home/home",
            });
          }, 1000);
          const langMap = {
            "zh-Hans": "zh",
            "zh-CN": "zh",
            zh: "zh",
            "zh-Hant": "zh-TW",
            "zh-TW": "zh-TW",
            en: "en",
            "en-US": "en",
            "en-GB": "en",
          };
          const rawLocale = uni.getStorageSync("locale") || uni.getLocale() || "zh";
          const locale = langMap[rawLocale] || "zh";
          // uni.setLocale(locale);
          uni.setStorageSync("locale", locale);
          uni.hideLoading();
        }
      }).catch(err => {
        console.log(err)
        uni.showToast({title: err.error, duration: 1500, icon: "error"});
      })
    } else {
      uni.showToast({title: res.error, duration: 1500, icon: "error"});
      uni.removeStorageSync("loginInfo");
      uni.hideLoading();
    }
  });
}
</script>

<style scoped lang="scss">

.version-container {
  position: absolute;
  bottom: 10rpx;
  width: 100%;
  display: flex;
  justify-content: center;

  span {
    font-size: .8rem;
    color: #8f8f94;
  }
}

.sun-index {
  background-color: #fff;
  min-height: calc(100vh - var(--window-top, 0px));
  width: 100%;
  box-sizing: border-box;
}

.sun-logo-box {
  display: flex;
  justify-content: center;
  flex-direction: column;
  width: 750rpx;
  height: 350rpx;
  box-sizing: border-box;
  padding-left: 60rpx;
}

.sun-logo {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 350rpx;
  height: 220rpx;
  border-radius: 15rpx;
}

.asset-img {
  height: 220rpx;
  width: 200rpx;
}

.logo-text {
  color: rgb(71, 146, 253);
  font-weight: bold;
  font-size: 72rpx;
  letter-spacing: 1px;
}

.input-label {
  font-size: 36rpx;
  color: #333;
  margin-left: 60rpx;
  margin-bottom: -20rpx;
  margin-top: 20rpx;
}

.login-form {
  .input-placeholder {
    font-size: 36rpx;
  }

  :deep(.up-input) {
    font-size: 36rpx;
  }

  :deep(.uni-input-input) {
    font-size: 36rpx;
  }

  :deep(.up-icon__icon) {
    font-size: 40rpx !important;
  }

  .up-input {
    height: 100rpx;
    border: 2rpx solid #ddd;
    border-radius: 15rpx;
  }
}

.login-code {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  margin: 40rpx 60rpx;
}

.login-code-images {
  margin-left: 30rpx;
}

.login-config {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  margin: 40rpx 60rpx;
}

.login-check {
  :deep(.u-checkbox__label-wrap span) {
    font-size: 36rpx !important;
  }
}

.login-btn-box {
  position: absolute;
  bottom: 100rpx;
  width: 100%;
  padding: 50rpx 60rpx 0;

  :deep(.login-btn) {
    height: 120rpx;
    border-radius: 15rpx;
  }

  :deep(.up-button__text) {
    font-size: 40rpx !important;
  }
}
</style>
